package project.order.weixi;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ConnectException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import net.sf.json.JSONObject;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



/**
 * @author Administrator
 * 微信工具类
 */
public class WxUtils {
	private static Logger logger = LoggerFactory.getLogger(WxUtils.class);

	/**
	 * 发起https请求并获取结果
	 * 
	 * @param requestUrl
	 *            请求地址
	 * @param requestMethod
	 *            请求方式（GET、POST）
	 * @param outputStr
	 *            提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */
	public static JSONObject httpRequest(String requestUrl,
			String requestMethod, String outputStr) {
		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
		try {
			// 创建SSLContext对象，并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
					.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod(requestMethod);

			if ("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();

			// 当有数据需要提交时
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(
					inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			jsonObject = JSONObject.fromObject(buffer.toString());
		} catch (ConnectException ce) {
			logger.error("Weixin server connection timed out.");
		} catch (Exception e) {
			logger.error("https request error:{}", e);
		}
		return jsonObject;
	}
	public static Map httpRequestXml(String requestUrl,
			String requestMethod, String outputStr) {
		Map<String, String> map = new HashMap<String, String>();
		StringBuffer buffer = new StringBuffer();
		try {
			// 创建SSLContext对象，并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
					.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod(requestMethod);
//			httpUrlConn.setRequestProperty(arg0, arg1)
			if ("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();
			// 当有数据需要提交时
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱码
				outputStream.write(outputStr.getBytes("utf-8"));//ISO8859-1
				outputStream.flush();
				outputStream.close();
				

				
//				String encode = "GBK";
//				OutputStreamWriter out = new OutputStreamWriter(httpUrlConn.getOutputStream(), encode);
//				out.write(requestUrl.toString());
//				out.flush();
//				out.close();
			}

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(
					inputStream, "utf-8");

			
			SAXReader reader = new SAXReader();
			Document document = reader.read(inputStream);
			
			Element root = document.getRootElement();
			List<Element> elementList = root.elements();

			for (Element element : elementList) {
				map.put(element.getName(), element.getText());
				
			}
			
			BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			System.out.println("发出xml后接收到的数据"+buffer.toString());


			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			
		} catch (ConnectException ce) {
			logger.error("Weixin server connection timed out.");
		} catch (Exception e) {
			logger.error("https request error:{}", e);
		}
		return map;
	}
	/**
	*@author Kenshinbo@163.com
	*@描述：map转XML
	*@param parameters
	*@return 
	*@version  WxUtils.java,v 1.1 Feb 10, 2015 11:25:57 PM KB
	*/
	public static String createXml2order(HashMap<String, String> parameters){
		StringBuffer xmlStr = new StringBuffer();
		xmlStr.append("<xml>");
		
		Iterator it = parameters.entrySet().iterator();

		while (it.hasNext()) {

			Map.Entry entry = (Map.Entry) it.next();
			xmlStr.append("<"+entry.getKey().toString().trim()+"><![CDATA["+entry.getValue().toString()+"]]></"+entry.getKey().toString().trim()+">");	
//			try {
//				xmlStr.append("<"+entry.getKey().toString().trim()+"><![CDATA["+URLEncoder.encode(entry.getValue().toString(), "utf-8")+"]]></"+entry.getKey().toString().trim()+">");
//			} catch (UnsupportedEncodingException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
		

		}
		
		
		xmlStr.append("</xml>");
		return xmlStr.toString();
	}
//	public static void main(String[] args) {
//		HashMap<String, String> parameters = new HashMap<String,String>();
//		parameters.put("notify_url", "http://www.shinner.cn/root/public/orderAction!paySuccess.action");
//		parameters.put("trade_type", "JSAPI");
//		parameters.put("mch_id", "1226244201");
//		String str = WxUtils.createXml2order(parameters);
//		System.out.println(str);
//	}
	public static void main(String[] args) {
		Map orderMap = WxUtils.httpRequestXml("https://api.mch.weixin.qq.com/pay/unifiedorder", "GET", "<xml><sign><![CDATA[A3255E8D7AD68AB8DF15CC2192C793CB]]></sign><body><![CDATA[orderzhishan]]></body><mch_id><![CDATA[1226244201]]></mch_id><spbill_create_ip><![CDATA[14.17.37.72]]></spbill_create_ip><total_fee><![CDATA[1]]></total_fee><notify_url><![CDATA[http://www.shinner.cn/root/public/orderAction!paySuccess.action]]></notify_url><appid><![CDATA[wx6e3f16241d2c490d]]></appid><openid><![CDATA[o5hCrjuIr_KRaOLE07JBURf0ZTLQ]]></openid><fee_type><![CDATA[CNY]]></fee_type><partner><![CDATA[1226244201]]></partner><out_trade_no><![CDATA[fbb8daae4b745016014b74523c310003]]></out_trade_no><trade_type><![CDATA[JSAPI]]></trade_type></xml>");
		System.out.println("收到的预下单Map:"+orderMap.get("prepay_id"));
    	if(null != orderMap.get("result_code")){
    		System.out.println("result_code="+orderMap.get("result_code"));	    		
    	}
    	if(null != orderMap.get("return_msg")){
    		System.out.println("return_msg="+orderMap.get("return_msg"));	    		
    	}
    	if(null != orderMap.get("err_code")){
    		System.out.println("err_code="+orderMap.get("err_code"));	    		
    	}
    	if(null != orderMap.get("err_code_des")){
    		System.out.println("err_code_des="+orderMap.get("err_code_des"));	    		
    	}
    	if(null != orderMap.get("prepay_id")){
    		System.out.println("prepay_id="+orderMap.get("prepay_id"));	   
	    	
    	}
	}
}
